//
//  StoreInfoViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/12.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "StoreInfoViewController.h"

@interface StoreInfoViewController ()
{
    UITextField *txtStoreName;
    UITextField *txtContacts;
    UITextField  *txtReceiver;
    UITextField *txtProvinceCityDistrict;
    UITextView *txtStoreAddtress;
}
@end

@implementation StoreInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"门店信息";
    self.view.backgroundColor = EastMarket_backgroundColor;
    [self initStoreInfoUI];
    [self loadViewCurrentInfo];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

- (void)initStoreInfoUI {

    CGFloat spacing = 8.0f;
    CGFloat border = 1.0f;
    // 背景ScrollView
    UIScrollView *applicationSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    applicationSV.showsVerticalScrollIndicator = YES;
    applicationSV.showsVerticalScrollIndicator = NO;
    applicationSV.backgroundColor = [UIColor clearColor];
    applicationSV.delegate = self;
    applicationSV.scrollEnabled = YES;
    [self.view addSubview:applicationSV];
    
    applicationSV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapapplicationSV = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyBoard:)];
    [applicationSV addGestureRecognizer:tapapplicationSV];

    UIView *viewStoreInfo = [[UIView alloc]initWithFrame:CGRectMake(0, spacing * 3, SCREEN_WIDTH, SCREEN_HEIGHT / 2)];
    viewStoreInfo.layer.cornerRadius = 3.0;
    viewStoreInfo.backgroundColor = [UIColor whiteColor];
    [applicationSV addSubview:viewStoreInfo];
    
    // 门店信息
    UILabel *lblStoreName = [[UILabel alloc]initWithFrame:CGRectMake(spacing, 0, (SCREEN_WIDTH - 2 * spacing) / 4, viewStoreInfo.frame.size.height / 6)];
    lblStoreName.text = @"门店名称";
    lblStoreName.textColor = [UIColor blackColor];
    lblStoreName.textAlignment = NSTextAlignmentLeft;
    lblStoreName.font = [UIFont systemFontOfSize:16];
    
    txtStoreName = [self createTextFielfFrame:CGRectMake(lblStoreName.frame.origin.x + lblStoreName.frame.size.width + spacing, lblStoreName.frame.origin.y, viewStoreInfo.frame.size.width - 3 * spacing - lblStoreName.frame.size.width, lblStoreName.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"门店名称"];
    txtStoreName.textAlignment = NSTextAlignmentRight;
    //    [txtInsureName setTextColor:[UIColor blackColor]];
    txtStoreName.delegate = self;
    txtStoreName.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line1=[self createImageViewFrame:CGRectMake(lblStoreName.frame.origin.x, lblStoreName.frame.origin.y + lblStoreName.frame.size.height - border, viewStoreInfo.frame.size.width - 2 * spacing, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 联系人
    UILabel *lblContacts = [[UILabel alloc] initWithFrame:CGRectMake(lblStoreName.frame.origin.x, lblStoreName.frame.origin.y + lblStoreName.frame.size.height, lblStoreName.frame.size.width, lblStoreName.frame.size.height)];
    lblContacts.text = @"联  系  人";
    lblContacts.textColor = [UIColor blackColor];
    lblContacts.textAlignment = NSTextAlignmentLeft;
    lblContacts.font = [UIFont systemFontOfSize:16];
    
    txtContacts = [self createTextFielfFrame:CGRectMake(txtStoreName.frame.origin.x, lblContacts.frame.origin.y, txtStoreName.frame.size.width, lblContacts.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"联系人"];
    txtContacts.textAlignment = NSTextAlignmentRight;
    txtContacts.delegate = self;
    txtContacts.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line2=[self createImageViewFrame:CGRectMake(line1.frame.origin.x, lblContacts.frame.origin.y + lblContacts.frame.size.height - border, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 收货人
    UILabel *lblReceiver = [[UILabel alloc] initWithFrame:CGRectMake(lblContacts.frame.origin.x, lblContacts.frame.origin.y + lblContacts.frame.size.height, lblContacts.frame.size.width, lblContacts.frame.size.height)];
    lblReceiver.text = @"收  货  人";
    lblReceiver.textColor = [UIColor blackColor];
    lblReceiver.textAlignment = NSTextAlignmentLeft;
    lblReceiver.font = [UIFont systemFontOfSize:16];
    
    txtReceiver = [self createTextFielfFrame:CGRectMake(txtStoreName.frame.origin.x, lblReceiver.frame.origin.y, txtContacts.frame.size.width, txtContacts.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"收货人"];
    txtReceiver.textAlignment = NSTextAlignmentRight;
    //    [txtInsureGender setTextColor:[UIColor blackColor]];
    txtReceiver.delegate = self;
    txtReceiver.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line3=[self createImageViewFrame:CGRectMake(line1.frame.origin.x, lblReceiver.frame.origin.y + lblReceiver.frame.size.height - border, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 省市区
    UILabel *lblProvinceCityDistrict = [[UILabel alloc] initWithFrame:CGRectMake(lblReceiver.frame.origin.x, lblReceiver.frame.origin.y + lblReceiver.frame.size.height, lblReceiver.frame.size.width, lblReceiver.frame.size.height)];
    lblProvinceCityDistrict.text = @"省  市  区";
    lblProvinceCityDistrict.textColor = [UIColor blackColor];
    lblProvinceCityDistrict.textAlignment = NSTextAlignmentLeft;
    lblProvinceCityDistrict.font = [UIFont systemFontOfSize:16];
    
    txtProvinceCityDistrict = [self createTextFielfFrame:CGRectMake(txtReceiver.frame.origin.x, lblProvinceCityDistrict.frame.origin.y, txtReceiver.frame.size.width, lblContacts.frame.size.height) font:[UIFont systemFontOfSize:16] placeholder:@"省市区"];
    txtProvinceCityDistrict.textAlignment = NSTextAlignmentRight;
    //    [txtInsureGender setTextColor:[UIColor blackColor]];
    txtProvinceCityDistrict.delegate = self;
    txtProvinceCityDistrict.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIImageView *line4=[self createImageViewFrame:CGRectMake(line1.frame.origin.x, lblProvinceCityDistrict.frame.origin.y + lblProvinceCityDistrict.frame.size.height - border, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 门店地址
    UILabel *lblStoreAddtress = [[UILabel alloc] initWithFrame:CGRectMake(lblProvinceCityDistrict.frame.origin.x, lblProvinceCityDistrict.frame.origin.y + lblProvinceCityDistrict.frame.size.height, lblContacts.frame.size.width, lblContacts.frame.size.height)];
    lblStoreAddtress.text = @"门店地址";
    lblStoreAddtress.textColor = [UIColor blackColor];
    lblStoreAddtress.textAlignment = NSTextAlignmentLeft;
    lblStoreAddtress.font = [UIFont systemFontOfSize:16];
    
    txtStoreAddtress = [self createTextViewfFrame:CGRectMake(txtReceiver.frame.origin.x, lblStoreAddtress.frame.origin.y, txtReceiver.frame.size.width, lblContacts.frame.size.height * 2) font:[UIFont systemFontOfSize:16] placeholder:@"门店地址"];
    txtStoreAddtress.textAlignment = NSTextAlignmentRight;
    //    [txtInsureGender setTextColor:[UIColor blackColor]];
    txtStoreAddtress.delegate = self;
    
    [viewStoreInfo addSubview:lblStoreName];
    [viewStoreInfo addSubview:txtStoreName];
    [viewStoreInfo addSubview:line1];
    
    [viewStoreInfo addSubview:lblReceiver];
    [viewStoreInfo addSubview:txtReceiver];
    [viewStoreInfo addSubview:line2];
    
    [viewStoreInfo addSubview:lblContacts];
    [viewStoreInfo addSubview:txtContacts];
    [viewStoreInfo addSubview:line3];
    
    [viewStoreInfo addSubview:lblProvinceCityDistrict];
    [viewStoreInfo addSubview:txtProvinceCityDistrict];
    [viewStoreInfo addSubview:line4];
    
    [viewStoreInfo addSubview:lblStoreAddtress];
    [viewStoreInfo addSubview:txtStoreAddtress];
    
    // 底部View
    UIView *viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, viewStoreInfo.frame.origin.y + viewStoreInfo.frame.size.height + 32, SCREEN_WIDTH, 49)];
    viewBottom.backgroundColor = [UIColor clearColor];
    [applicationSV addSubview:viewBottom];
    
    UIButton *btnConfirm = [UIButton buttonWithType:UIButtonTypeSystem];
    btnConfirm.frame = CGRectMake(16 * 2, 4, viewBottom.frame.size.width - 16 * 4, viewBottom.frame.size.height - 2 * 4);
    btnConfirm.backgroundColor = EastMarket_MainToneColor;
    [btnConfirm setTitle:@"保存" forState:UIControlStateNormal];
    [btnConfirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnConfirm.titleLabel setFont:[UIFont systemFontOfSize:18]];
    btnConfirm.layer.cornerRadius = 5.0f;
    [btnConfirm addTarget:self action:@selector(btnConfirmClicked:) forControlEvents:UIControlEventTouchUpInside];
    [viewBottom addSubview:btnConfirm];
    
    applicationSV.contentSize = CGSizeMake(SCREEN_WIDTH, viewBottom.frame.origin.y + viewBottom.frame.size.height + TopBarHeight + TabBarHeight);
}

- (void)loadViewCurrentInfo {
    
    [NSThread detachNewThreadSelector:@selector(callServeretCurrentInfo) toTarget:self withObject:Nil];
}
-(void)callServeretCurrentInfo
{
    NSDictionary *dic = [AppServiceInterface GetCurrentAccountInfo];
    [self performSelectorOnMainThread:@selector(updateUIAftGetCurrentAccountInfo:) withObject:dic waitUntilDone:false];
}

-(void)updateUIAftGetCurrentAccountInfo:(NSDictionary *)dic {
    
    [SVProgressHUD dismiss];
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        _dicStoreInfo = [dic objectForKey:@"data"];
        
        if (![[_dicStoreInfo objectForKey:@"shopName"] isKindOfClass:[NSNull class]]) {
            txtStoreName.text = [NSString stringWithFormat:@"%@", [_dicStoreInfo objectForKey:@"shopName"]];
        }
        if (![[_dicStoreInfo objectForKey:@"contactName"] isKindOfClass:[NSNull class]]) {
            txtContacts.text = [NSString stringWithFormat:@"%@", [_dicStoreInfo objectForKey:@"contactName"]];
        }
        if (![[_dicStoreInfo objectForKey:@"consignee"] isKindOfClass:[NSNull class]]) {
            txtReceiver.text = [NSString stringWithFormat:@"%@", [_dicStoreInfo objectForKey:@"consignee"]];
        }
        if (![[_dicStoreInfo objectForKey:@"region"] isKindOfClass:[NSNull class]]) {
            txtProvinceCityDistrict.text = [NSString stringWithFormat:@"%@", [_dicStoreInfo objectForKey:@"region"]];
        }
        if (![[_dicStoreInfo objectForKey:@"shopAddress"] isKindOfClass:[NSNull class]]) {
            txtStoreAddtress.text = [NSString stringWithFormat:@"%@", [_dicStoreInfo objectForKey:@"shopAddress"]];
        }
    } else if (dic && !([[dic objectForKey:@"success"] integerValue] == 1)) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
        return;
    } else {
        
        [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后重试"];
        return;
    }
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    textField.font=font;
    textField.textColor=[UIColor grayColor];
    textField.borderStyle=UITextBorderStyleNone;
    textField.placeholder=placeholder;
    
    return textField;
}

-(UITextView *)createTextViewfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextView *textView=[[UITextView alloc]initWithFrame:frame];
    textView.font=font;
    textView.textColor=[UIColor grayColor];
    
    return textView;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

- (void)hidenKeyBoard {

    [txtStoreName resignFirstResponder];
    [txtContacts resignFirstResponder];
    [txtReceiver resignFirstResponder];
    [txtProvinceCityDistrict resignFirstResponder];
    [txtStoreAddtress resignFirstResponder];
}

- (void)hidenKeyBoard:(UIGestureRecognizer *)tap {
    
    [txtStoreName resignFirstResponder];
    [txtContacts resignFirstResponder];
    [txtReceiver resignFirstResponder];
    [txtProvinceCityDistrict resignFirstResponder];
    [txtStoreAddtress resignFirstResponder];
    //键盘收回后视图移动回原位的动画
    [UIView animateWithDuration:0.3 animations:^{
        
        float width = self.view.frame.size.width;
        float hight = self.view.frame.size.height;
        
        CGRect rect = CGRectMake(0, 44 + 20, width, hight);
        self.view.frame = rect;
    }];
}

- (void)btnConfirmClicked:(UIButton *)btn {

    debugMethod();
    [self loadUpdateMemberInfo];
    
}

- (void)loadUpdateMemberInfo {
    
    [NSThread detachNewThreadSelector:@selector(callServerUpdateMemberInfo) toTarget:self withObject:Nil];
}
- (void)callServerUpdateMemberInfo {
    
    NSDictionary *dicAfterUpdateMemberInfo = [AppServiceInterface updateCurrentAccountInfo:txtStoreName.text contactName:txtContacts.text shopAddress:txtStoreAddtress.text consignee:txtReceiver.text region:txtProvinceCityDistrict.text];
    
    [self performSelectorOnMainThread:@selector(updateCurrentAccountRankUI:) withObject:dicAfterUpdateMemberInfo waitUntilDone:NO];
}

- (void)updateCurrentAccountRankUI:(NSDictionary *)dict {
    if (dict &&  [[dict objectForKey:@"success"] integerValue] == 1) {
        debugLog(@"%@", dict);
        NSNotification *notice = [NSNotification notificationWithName:NotificationLoginSccess object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
        [self.navigationController popViewControllerAnimated:true];
    } else if(dict &&  [[dict objectForKey:@"success"] integerValue] != 1) {
    
        [GlobalUnit showAlertHint:@"温馨提示" message:[dict objectForKey:@"msg"]];
        
    } else {
        [GlobalUnit showAlertHint:@"温馨提示" message:@"连接服务器失败，请稍后重试！"];
        return;
    }
}
#pragma mark -- UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (textField == txtProvinceCityDistrict) {
        [self hidenKeyBoard];
        [self PickerAddress];
        return NO;
    } else {
    
        return YES;
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldFrame      = textField.frame;
    //当前输入框的Y
    CGFloat textField_Y        = textFieldFrame.origin.y;
    //当前输入框的高度
    CGFloat textFieldHight     = textFieldFrame.size.height;
    //屏幕高度
    CGFloat screenHight        = self.view.frame.size.height;
    //键盘高度
    //    CGFloat keyBordHight       = keyBordHight;
    //键盘tabbar高度
    CGFloat keyBordTabbarHight = 49;
    //计算输入框向上移动的偏移量
    int offset = textField_Y + textFieldHight + 64 - (screenHight - KeyboardHeight - keyBordTabbarHight);
    
    //根据键盘遮挡的高度开始移动动画
    [UIView animateWithDuration:0.3 animations:^{
        if (offset > 0) {
            
            float width = self.view.frame.size.width;
            float hight = self.view.frame.size.height;
            
            CGRect rect = CGRectMake(0, -offset, width, hight);
            self.view.frame = rect;
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    //键盘收回后视图移动回原位的动画
    [UIView animateWithDuration:0.3 animations:^{
        
        float width = self.view.frame.size.width;
        float hight = self.view.frame.size.height;
        
        CGRect rect = CGRectMake(0, 44 + 20, width, hight);
        self.view.frame = rect;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    //点击Return,键盘收回后视图移动回原位的动画
    [UIView animateWithDuration:0.3 animations:^{
        
        float width = self.view.frame.size.width;
        float hight = self.view.frame.size.height;
        
        CGRect rect = CGRectMake(0, 44 + 20, width, hight);
        self.view.frame = rect;
    }];
    return YES;
}

#pragma mark -- UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [txtStoreAddtress resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    return YES;
}

// 地址选择器
- (void)PickerAddress {
    
    if (self.pickerView) {
        self.pickerView.hidden = NO;
        return;
    }
    self.pickerView = [[GuoguoAddressPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 280, SCREEN_WIDTH, 280)];
    [self.pickerView updateAddressAtProvince:@"福建省" city:@"厦门市" town:@"集美区"];
    self.pickerView.delegate = self;
    self.pickerView.font = [UIFont boldSystemFontOfSize:14];
    [self.view addSubview:self.pickerView];
}

- (void)GuoguoAddressCancleAction:(id)senter {
    self.pickerView.hidden = YES;
}

- (void)GuoguoAddressPickerRerurnBlockWithProvince:(NSString *)province city:(NSString *)city town:(NSString *)town {
    self.pickerView.hidden = YES;
    debugLog(@"%@  %@  %@",province,city,town);
    txtProvinceCityDistrict.text = [NSString stringWithFormat:@"%@，%@，%@", province, city, town];
}

- (void)setPickerView:(GuoguoAddressPickerView *)pickerView {
    if (!_pickerView) {
        
    }
    _pickerView = pickerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
